package com.prj.ufdm.cloud.ms.auth.api;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.prj.ufdm.cloud.base.dto.RetData;
import com.prj.ufdm.cloud.base.exception.BaseException;
import com.prj.ufdm.cloud.base.util.BaseDateUtil;
import com.prj.ufdm.cloud.base.util.BaseMd5Util;
import com.prj.ufdm.cloud.base.util.BaseStringUtil;
import com.prj.ufdm.cloud.base.util.BaseUuidUtil;
import com.prj.ufdm.cloud.ms.auth.bpo.SysOrganBPO;
import com.prj.ufdm.cloud.ms.auth.bpo._impl.SysUserBPOImpl;
import com.prj.ufdm.cloud.ms.auth.enums.AuthRetCodeEnum;
import com.prj.ufdm.cloud.ms.auth.enums.SysUserStatusEnum;
import com.prj.ufdm.cloud.ms.auth.model.SysOrgan;
import com.prj.ufdm.cloud.ms.auth.model.SysUser;
import com.prj.ufdm.cloud.ms.core.bpo.SeqNumBPO;
import com.prj.ufdm.cloud.ms.core.enums.CodeGenerateEnum;
import com.prj.ufdm.cloud.ms.core.model.PageBean;
import com.prj.ufdm.cloud.ms.core.model.SeqNum;

/**
 * 用户管理控制类
 * @author 胡义振  
 * @date 2018年3月26日
 */
@RequestMapping(value = "/api/auth/sysuser")
@Controller
public class SysUserController {
	
	@Autowired
	private SysUserBPOImpl sysUserBPO;
	
	@Autowired
	private SysOrganBPO sysOrganBPO;
	
	@Autowired
	private SeqNumBPO seqNumBPO;
	
	/**
	 * Desc: 查询所有系统用户
	 * @param 
	 *     sysUser 系统用户对象 （为空 查询所有）
	 *     pageBean 分页查询对象
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetList")
	@ResponseBody
	public RetData<PageInfo<SysUser>> doGetList(SysUser sysUser,PageBean pageBean) throws Exception {
		
		// 判断是否需要根据机构递归查询
		if("1".equals(sysUser.getOrganRecurFlag())) {
			if(sysUser.getOrganId()!=null && !sysUser.getOrganId().equals("")) {
				Set<String> setOrganId = new HashSet<String>();
				sysOrganBPO.getChildrenOrgan(sysUser.getOrganId(), setOrganId, 0);
				List<SysOrgan> listOrganId = new ArrayList<SysOrgan>();
				SysOrgan sysOrgan = new SysOrgan();
				sysOrgan.setId(sysUser.getOrganId());
				listOrganId.add(sysOrgan);
				setOrganId.forEach(s ->  {
					SysOrgan obj = new SysOrgan();
					obj.setId(s);
					listOrganId.add(obj);
				});
				sysUser.setListSysOrgan(listOrganId);
			}
		}
		
		RetData<PageInfo<SysUser>> retData = new RetData<PageInfo<SysUser>>();
		PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
		List<SysUser> listSysUser = sysUserBPO.doGetList(sysUser);
		for (SysUser sys : listSysUser) {
			sys.setUserStatusMc(SysUserStatusEnum.getMessageByCode(sys.getUserStatus()));
		}
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(listSysUser);
		retData.setRetBody(pageInfo);
		return retData;
	}
	
	/**
	 * Desc: 查询机构下所有用户(所属机构与机构机构用户)
	 * @param 
	 *     sysUser 系统用户对象 （为空 查询所有）
	 *     pageBean 分页查询对象
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetOrganAllSysUserList")
	@ResponseBody
	public RetData<PageInfo<SysUser>> doGetOrganAllSysUserList(SysUser sysUser,PageBean pageBean) throws Exception {
		// 判断是否需要根据机构递归查询
		if("1".equals(sysUser.getOrganRecurFlag())) {
			if(sysUser.getOrganId()!=null && !sysUser.getOrganId().equals("")) {
				Set<String> setOrganId = new HashSet<String>();
				sysOrganBPO.getChildrenOrgan(sysUser.getOrganId(), setOrganId, 0);
				List<SysOrgan> listOrganId = new ArrayList<SysOrgan>();
				SysOrgan sysOrgan = new SysOrgan();
				sysOrgan.setId(sysUser.getOrganId());
				listOrganId.add(sysOrgan);
				setOrganId.forEach(s ->  {
					SysOrgan obj = new SysOrgan();
					obj.setId(s);
					listOrganId.add(obj);
				});
				sysUser.setListSysOrgan(listOrganId);
			}
		}
		RetData<PageInfo<SysUser>> retData = new RetData<PageInfo<SysUser>>();
		PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
		List<SysUser> listSysUser = sysUserBPO.doGetOrganAllSysUserList(sysUser);
		for (SysUser sys : listSysUser) {
			sys.setUserStatusMc(SysUserStatusEnum.getMessageByCode(sys.getUserStatus()));
		}
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(listSysUser);
		retData.setRetBody(pageInfo);
		return retData;
	}
	
	/**
	 * Desc: 查询当前用户
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetUser")
	@ResponseBody
	public RetData<SysUser> doGetUser(SysUser sysUser) throws Exception {
		RetData<SysUser> retData = new RetData<SysUser>();
		SysUser user = sysUserBPO.doGetById(sysUser.getId());
		retData.setRetBody(user);
		return retData;
	}
	
	
	/**
	 * Desc: 查询角色用户
	 * @param 
	 *     sysUser 系统用户对象 （为空 查询所有）
	 *     pageBean 分页查询对象
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetListWithRoleId")
	@ResponseBody
	public RetData<PageInfo<SysUser>> doGetListWithRoleId(SysUser sysUser,PageBean pageBean) throws Exception {
		
		if(sysUser==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getRoleId()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0103001.getCode(),AuthRetCodeEnum.RET_CODE_0103001.getMessage());
		}
		RetData<PageInfo<SysUser>> retData = new RetData<PageInfo<SysUser>>();
		PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
		List<SysUser> listSysUser = sysUserBPO.doGetSysUserListWithRoleId(sysUser);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(listSysUser);
		retData.setRetBody(pageInfo);
		return retData;
	}
	
	/**
	 * Desc: 查询职务用户
	 * @param 
	 *     sysUser 系统用户对象 （为空 查询所有）
	 *     pageBean 分页查询对象
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetSysUserListWithDutyId")
	@ResponseBody
	public RetData<PageInfo<SysUser>> doGetSysUserListWithDutyId(SysUser sysUser,PageBean pageBean) throws Exception {
		
		if(sysUser==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getDutyId()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0105001.getCode(),AuthRetCodeEnum.RET_CODE_0105001.getMessage());
		}
		RetData<PageInfo<SysUser>> retData = new RetData<PageInfo<SysUser>>();
		PageHelper.startPage(pageBean.getPageNum(),pageBean.getPageSize());
		List<SysUser> listSysUser = sysUserBPO.doGetSysUserListWithDutyId(sysUser);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(listSysUser);
		retData.setRetBody(pageInfo);
		return retData;
	}
	
	
	
	/**
	 * Desc: 根据机构id查询用户
	 * 
	 * @param sysUser 系统用户对象 （为空 查询所有） pageBean 分页查询对象
	 * @return
	 * 
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doGetListWithOrganId")
	@ResponseBody
	public RetData<PageInfo<SysUser>> doGetListWithOrganId(SysUser sysUser, PageBean pageBean) throws Exception {

//		if (sysUser == null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getOrganCode()))) {
//			throw new BaseException(AuthRetCodeEnum.RET_CODE_0103003.getCode(),
//					AuthRetCodeEnum.RET_CODE_0103003.getMessage());
//		}
		RetData<PageInfo<SysUser>> retData = new RetData<PageInfo<SysUser>>();
		PageHelper.startPage(pageBean.getPageNum(), pageBean.getPageSize());
		List<SysUser> listSysUser = sysUserBPO.doGetSysUserListWithOrganId(sysUser);
		PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(listSysUser);
		retData.setRetBody(pageInfo);
		return retData;
	}
	
	
	/**
	 * Desc: 保存系统用户
	 * @param sysUser 
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doSave")
	@ResponseBody
	public RetData<String> doSave(SysUser sysUser) throws Exception {
		RetData<String> retData = new RetData<String>();
		if(SysUserStatusEnum.SYSUSER_STATUS_1.getCode().equals(sysUser.getUserStatus())) {
			// 用户名不能为空
			if(sysUser==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getUsername()))) {
				throw new BaseException(AuthRetCodeEnum.RET_CODE_0102001.getCode(),AuthRetCodeEnum.RET_CODE_0102001.getMessage());
			}
			else {
				// 密码不能为空
				if("".equals(BaseStringUtil.replaceAllBlank(sysUser.getPassword()))) {
					throw new BaseException(AuthRetCodeEnum.RET_CODE_0102002.getCode(),AuthRetCodeEnum.RET_CODE_0102002.getMessage());
				}
				// 用户名已存在
				if(sysUserBPO.doCheckSysUserLoginNameExist(sysUser.getUsername(), "")) {
					throw new BaseException(AuthRetCodeEnum.RET_CODE_0102003.getCode(),AuthRetCodeEnum.RET_CODE_0102003.getMessage());
				}
			}
		}
		String userId=BaseUuidUtil.getUUID();
		sysUser.setId(userId);
		 //生成编码
		SeqNum seqNum=new SeqNum();
		seqNum.setCodeType(CodeGenerateEnum.USER_CODE_GENERATE.getMessage());
        String userCode=seqNumBPO.generateCode(seqNum);
        if(StringUtils.isBlank(userCode)) {
        	throw new BaseException("用户编码生成失败，联系管理员！");
        }
        sysUser.setUserCode(userCode);
		sysUser.setPassword(BaseMd5Util.MD5Encode(sysUser.getPassword()));
		sysUser.setCreateTime(BaseDateUtil.getCurrentTime());
		if(!StringUtils.isBlank(sysUser.getOrganId())) {
			//通过机构id查询机构对象
			SysOrgan organ=sysOrganBPO.selectByOrganId(sysUser.getOrganId());
			if(organ!=null) {
				sysUser.setOrganName(organ.getOrganName());
				sysUser.setOrganCode(organ.getOrganCode());
			}
		}
		sysUserBPO.doSave(sysUser);	
		return retData;
	}
	
	/**
	 * Desc: 修改用户信息
	 * @param sysUser 
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doMod")
	@ResponseBody
	public RetData<String> doMod(SysUser sysUser) throws Exception {
		RetData<String> retData = new RetData<String>();
		// 用户ID不能为空
		if(sysUser==null || sysUser.getId()==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getId()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102004.getCode(),AuthRetCodeEnum.RET_CODE_0102004.getMessage());
		}
		
		// 检查用户ID是否存在
		if(sysUserBPO.doGetById(sysUser.getId())==null) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102005.getCode(),AuthRetCodeEnum.RET_CODE_0102005.getMessage());
		}
		if(SysUserStatusEnum.SYSUSER_STATUS_1.getCode().equals(sysUser.getUserStatus())) {
			// 用户名不能为
			if("".equals(BaseStringUtil.replaceAllBlank(sysUser.getUsername()))) {
				throw new BaseException(AuthRetCodeEnum.RET_CODE_0102001.getCode(),AuthRetCodeEnum.RET_CODE_0102001.getMessage());
			}
			
			// 用户名已存在
			else if(sysUserBPO.doCheckSysUserLoginNameExist(sysUser.getUsername(), sysUser.getId())) {
				throw new BaseException(AuthRetCodeEnum.RET_CODE_0102003.getCode(),AuthRetCodeEnum.RET_CODE_0102003.getMessage());
			}
		}
		// 密码为空，不修改密码
		if(!"".equals(BaseStringUtil.replaceAllBlank(sysUser.getPassword()))) {
		    sysUser.setPassword(BaseMd5Util.MD5Encode(sysUser.getPassword()));
		}
		if(!StringUtils.isBlank(sysUser.getOrganId())) {
			//通过机构id查询机构对象
			SysOrgan organ=sysOrganBPO.selectByOrganId(sysUser.getOrganId());
			if(organ!=null) {
				sysUser.setOrganName(organ.getOrganName());
				sysUser.setOrganCode(organ.getOrganCode());
			}
			//通过用户id查询用户，
			SysUser user=sysUserBPO.doGetById(sysUser.getId());
			if(user==null) {
				throw new BaseException("通过用户id，查询用户失败！");
			}
		}
		sysUserBPO.doModById(sysUser);
		return retData;
	}
	
	/**
	 * Desc: 修改用户密码
	 * @param sysUser 
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doModPass")
	
	@ResponseBody
	public RetData<String> doModPass(SysUser sysUser) throws Exception {
		RetData<String> retData = new RetData<String>();
		// 用户名不能为空
		if(sysUser==null || sysUser.getUsername()==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getUsername()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102001.getCode(),AuthRetCodeEnum.RET_CODE_0102001.getMessage());
		}
		// 原密码不能为空
		if(sysUser==null || sysUser.getOldPassword()==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getOldPassword()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102006.getCode(),AuthRetCodeEnum.RET_CODE_0102006.getMessage());
		}
		// 新密码不能为空
		if(sysUser==null || sysUser.getPassword()==null || "".equals(BaseStringUtil.replaceAllBlank(sysUser.getPassword()))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102002.getCode(),AuthRetCodeEnum.RET_CODE_0102002.getMessage());
		}
		// 检查老密码是否正确
		SysUser validSysUser = sysUserBPO.doGetSysUserByUserNameAndPassword(sysUser.getUsername(), BaseMd5Util.MD5Encode(sysUser.getOldPassword()));
		if(validSysUser==null) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102007.getCode(),AuthRetCodeEnum.RET_CODE_0102007.getMessage());
		}
		validSysUser.setPassword(BaseMd5Util.MD5Encode(sysUser.getPassword()));
		validSysUser.setUpdatePasswordTime(new Date());
		sysUserBPO.doModById(validSysUser);
		retData.setRetBody("密码修改成功");
		return retData;
	}

	
	/**
	 * Desc: 删除用户
	 * @param id 要删除的用户ID（多个ID，逗号分隔）
	 * @return
	 * @author 胡义振  
	 * @date 2018年3月26日
	 */
	@RequestMapping(value = "/doDel")
	@ResponseBody
	public RetData<String> doDelRole(String id) throws Exception {
		RetData<String> retData = new RetData<String>();
		sysUserBPO.doRmSysUserById(id);
		return retData;
	}
	
	@RequestMapping(value = "/doGetSysUserByUserName")
	@ResponseBody
	public RetData<SysUser> doGetSysUserByUserName(String username) throws Exception {
		RetData<SysUser> retData = new RetData<SysUser>();
		// 用户ID不能为空
		if("".equals(BaseStringUtil.replaceAllBlank(username))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0102001.getCode(),AuthRetCodeEnum.RET_CODE_0102001.getMessage());
		}
		SysUser sysUser = sysUserBPO.doGetSysUserByUsername(username);
		if(sysUser==null) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0101002.getCode(),AuthRetCodeEnum.RET_CODE_0102001.getMessage());
		}
		retData.setRetBody(sysUser);
		return retData;
	}
	
	@RequestMapping(value = "/doGetSysUserByToken")
	@ResponseBody
	public RetData<SysUser> doGetSysUserByToken(String token) throws Exception {
		RetData<SysUser> retData = new RetData<SysUser>();
		// 用户ID不能为空
		if("".equals(BaseStringUtil.replaceAllBlank(token))) {
			throw new BaseException(AuthRetCodeEnum.RET_CODE_0101008.getCode(),AuthRetCodeEnum.RET_CODE_0101008.getMessage());
		}
		retData.setRetBody(sysUserBPO.doGetSysUserByToken(token));
		return retData;
	}
	
	
	/**
	 * 提示长期未修改密码
	 */
	@RequestMapping(value = "/promptUpdatePassword")
	@ResponseBody
	public RetData<String> promptUpdatePassword(SysUser sysUser) throws Exception {
		RetData<String> retData = new RetData<String>();
		SysUser user = sysUserBPO.doGetById(sysUser.getId());
		Date date1 = user.getUpdatePasswordTime();
		if (date1 != null) {
			Date date2 = new Date();
			Long i = (date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24);
			if (i > 30) {
				retData.setRetBody("长期未修改密码，请修改密码");
			}
		} else {
			retData.setRetBody("为了你的账号安全，请修改密码");
		}
		return retData;
	}
	
}
